import {Component} from '@angular/core';
import {AlertController, IonicPage, NavController, NavParams} from 'ionic-angular';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {UserService} from "../../services/user.service";

@IonicPage()
@Component({
  selector: 'page-extract',
  templateUrl: 'extract.html',
})
export class ExtractPage {

  public validateForm: FormGroup = this.fb.group({
    num: [null, [Validators.required]],
  });//登录的表单
  public isRefresh: boolean = true;

  constructor(public navCtrl: NavController, public navParams: NavParams,
              private fb: FormBuilder, private alertCtrl: AlertController,
              private userService: UserService) {
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad ExtractPage');
  }

  public extract($event) {
    $event.preventDefault();
    let me = this;
    for (const key in me.validateForm.controls) {
      me.validateForm.controls[key].markAsDirty();
      me.validateForm.controls[key].updateValueAndValidity();
    }
    if (me.validateForm.invalid) return;
    this.passwordPrompt();
  };

  passwordPrompt() {
    this.isRefresh = false;
    let alert = this.alertCtrl.create({
      title: '交易密码',
      inputs: [
        {
          name: 'password',
          type: 'password',
          placeholder: '请输入交易密码'
        }
      ],
      buttons: [
        {
          text: '确认',
          handler: data => {
            if (!data.password || data.password === '') return false;
            else {
              let formData = Object.assign(this.validateForm.value);
              formData.pinPassword = data.password;
              this.refineOre(formData);
            }
          }
        }
      ]
    });
    alert.present();
  }

  /**
   * 提炼矿石
   * @param formData
   */
  refineOre(formData) {
    this.userService.refineOre(formData).then(res => {
      this.isRefresh = true;
    }).catch(err => {
      return false;
    });
  }

  getFormControl(name) {
    return this.validateForm.controls[name];
  }
}
